#include "func.h"
#include <unistd.h>

int main()
{
    //1.socket
    int clientfd = socket(AF_INET,SOCK_STREAM,0);
    if(clientfd < 0){
        perror("socket");
        return EXIT_FAILURE;
    }

    //2.connect
    struct sockaddr_in serveraddr;
    memset(&serveraddr,0,sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(12345);
    serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    int ret = connect(clientfd,(const struct sockaddr*)&serveraddr,sizeof(serveraddr));
    if(ret < 0){
        perror("connect");
        close(clientfd);
        return EXIT_FAILURE;
    }
    printf("connect success\n");


    fd_set readfds;
    FD_ZERO(&readfds);
    FD_SET(clientfd, &readfds); 
    FD_SET(STDIN_FILENO, &readfds); 
    int max_fd = clientfd;
    char buf[1024] = {0};

    while(1){
        fd_set readyset = readfds;
        ret = select(max_fd+1, &readyset,NULL,NULL,NULL);
        if(ret == -1){
            perror("select");
            continue;
        }

        if(FD_ISSET(clientfd,&readyset)){
            memset(buf,0,sizeof(buf));
            ret = recv(clientfd,buf,sizeof(buf),0);
            if(ret == 0){
                printf("server disconneted.\n");
                close(clientfd);
                break;
            }
            printf("recv %d bytes \nrecv : %s \n",ret,buf);

        }

        if(FD_ISSET(STDIN_FILENO,&readyset)){
            memset(buf,0,sizeof(buf));
            int ret = read(STDIN_FILENO,buf,sizeof(buf));
            ret = send(clientfd, buf,strlen(buf),0); 
            printf("send %d bytes \n",ret);
        }
    }


    return 0;
}

